package com.css.dzj.dzjfxyj.modules.reply.service.Impl;

import com.css.dzj.dzjfxyj.common.util.Constant;
import com.css.dzj.dzjfxyj.common.util.R;
import com.css.dzj.dzjfxyj.common.util.ServiceUtil;
import com.css.dzj.dzjfxyj.modules.acquier.entity.JgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.entity.QJgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.service.AcquierService;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.JgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.QJgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.mapper.replyMapper;
import com.css.dzj.dzjfxyj.modules.reply.service.replyService;
import com.css.dzj.dzjfxyj.modules.reply.vo.ReplyVo.ReplyVo;
import com.css.dzj.dzjfxyj.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class replyServiceImpl implements replyService {
    @Autowired
    private replyMapper replyMapper;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    private AcquierService acquierService;

    @Autowired
    private ServiceUtil serviceUtil;

    @Override
    public QueryResults<JgFxyjWarningSignalEntity> getAllReply(Pageable pageable) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;

        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.dispenseState.eq(Constant.YIDISTRIBUTE));
        predicate = ExpressionUtils.and(predicate, q.overState.eq(Constant.DAIREPLY));
        return  jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    @Override
    public ReplyVo queryOne(String fxyjId) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        JgFxyjWarningSignalEntity fetchOne = jpaQueryFactory
                                            .selectFrom(q)
                                            .where(q.fxyjId.eq(fxyjId)
                                            //q..delFlag.eq(Constant.NO_DELETE)
                                            )
                                            .fetchOne();
        ReplyVo replyVo = new ReplyVo();
        replyVo.setRiskwarning(fetchOne);
        //replyVo.setJgFxyjWarningSignalEntity(fetchOne);
        QJgFxyjFeedbackEntity qreply = QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        List<JgFxyjFeedbackEntity> list = jpaQueryFactory
                .selectFrom(qreply)
                .where(qreply.fxyjId.eq(fxyjId))
                .orderBy(
                        // 根据创建日期，降序排序
                        qreply.createTime.desc()
                ).fetch();
        replyVo.setRiskwarningChildren(list);
        //replyVo.setJgFxyjFeedbackEntityList(list);
        return replyVo;
    }

    @Override
    @Transactional
    public String addReply(ReplyVo vo, HttpServletRequest request) {
        try {
            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String location = "";
            String address="";
            String orgName = "";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
                address = userInfo.getAddress();
            }

            List<JgFxyjFeedbackEntity> list = vo.getRiskwarningChildren();
            JgFxyjWarningSignalEntity jws = vo.getRiskwarning();
            List<JgFxyjFeedbackEntity> listsave = new ArrayList<>();
            for(int i=0;i<list.size();i++){
                JgFxyjFeedbackEntity jfe = list.get(i);
                jfe.setCreateTime(new Date());
                jfe.setTaskId(jws.getId());
                jfe.setCreatePreson(suserName);
                jfe.setResponseTime(new Date());
                listsave.add(jfe);
            }
            replyMapper.saveAll(listsave);
            updHuifuState(jws.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 修改回复状态
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R updHuifuState(String id) {
        try {
            if(!"".equals(id) && id!=null){
                QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
                jpaQueryFactory.update(q)
                        .set(q.revertState, Constant.YIREPLY).set(q.dealState,Constant.YIFANKUI)
                        .where(q.id.eq(id))
                        .execute();
                System.out.println();
                return R.ok();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    @Override
    public QueryResults<JgFxyjWarningSignalEntity> getPage(Pageable pageable, String fxyjDomainId, String fxyjTitle, String fxyjLevel, String fxyjObjectName, String startTime, String endTime, String startTime1, String endTime1) {
        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (fxyjDomainId == null || fxyjDomainId.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (fxyjTitle == null || fxyjTitle.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (fxyjLevel == null || fxyjLevel.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (fxyjObjectName == null || fxyjObjectName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%"+fxyjObjectName.trim()+"%"));
        predicate = ExpressionUtils.and(predicate, q.dispenseState.eq(Constant.YIDISTRIBUTE));
        predicate = ExpressionUtils.and(predicate, q.overState.eq(Constant.DAIREPLY));

        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse("2010-12-30");
                endDate = sf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println();
            try {
                startDate = sf.parse(startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                System.out.println();
                startDate = sf.parse(startTime);
                endDate = sf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.between(startDate,endDate));
        }

        if((StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse("2010-12-30");
                endDate = sf.parse(endTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                System.out.println();
                startDate = sf.parse(startTime1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                System.out.println();
                startDate = sf.parse(startTime1);
                endDate = sf.parse(endTime1);
                System.out.println();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }

        return jpaQueryFactory.selectFrom(q).
                where(predicate).
                orderBy(q.createTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();
    }

    /**
     * 通过风险预警线索唯一ID
     * 查询详细信息
     */
    @Override
    public ReplyVo queryAcquire(String id,String from,HttpServletRequest request) {
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String orgName = "";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();
            location = orgName.replace("地震局","");
            address = userInfo.getAddress();
        }
        ReplyVo replyVo = new ReplyVo();
        JgFxyjWarningSignalEntity acquire = acquierService.findById(id);
        JgFxyjFeedbackEntity reply = new JgFxyjFeedbackEntity();
        reply.setFxyjId(acquire.getFxyjId());
        reply.setFxyjObjectType(acquire.getFxyjObjectType());
        reply.setFxyjObjectId(acquire.getFxyjObjectId());
        reply.setFxyjOperator(suserName);
        reply.setFxyjOperatorType(orgName);
        List<JgFxyjFeedbackEntity> replys = queryList(acquire.getId());
        if (replys==null || replys.size()<=0){
            reply.setFxyjFeedbackId("001");
        }else {
           int fint = replys.size()+1;
           int g = fint/10;
           if (g==0){
               reply.setFxyjFeedbackId("00"+fint);
           }else {
               int s = g / 10;
               if (s == 0) {
                   reply.setFxyjFeedbackId("0" + fint);
               } else {
                   reply.setFxyjFeedbackId("" + fint);
               }
           }
        }
        if ("over".equals(from)){
            reply.setFxyjResult("3");
            reply.setFxyjEnd(new Date());
        }else {
            reply.setFxyjResult("2");
            reply.setResponseTime(new Date());
        }
        List<JgFxyjFeedbackEntity> list = new ArrayList<>();
        list.add(reply);
        replyVo.setRiskwarning(acquire);
        replyVo.setRiskwarningChildren(list);
        return replyVo;
    }

    @Override
    public List<JgFxyjFeedbackEntity> queryList(String id) {
        QJgFxyjFeedbackEntity qreply = QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        List<JgFxyjFeedbackEntity> list = jpaQueryFactory
                .selectFrom(qreply)
                .where(qreply.taskId.eq(id))
                .orderBy(
                        // 根据创建日期，降序排序
                        qreply.createTime.desc()
                ).fetch();
        return list;
    }

}
